home *** CD-ROM | disk | FTP | other *** search
- Path: news.ccs.queensu.ca!news
- From: Wintermute <3mal5@qlink.queensu.ca>
- Newsgroups: comp.lang.c++
- Subject: Re: Trouble w/ random numbers...please help
- Date: 6 Feb 1996 05:55:11 GMT
- Organization: System Infinity
- Message-ID: <4f6qfv$c4m@knot.queensu.ca>
- References: <4f0g5u$879@ns.campus.mci.net> <DMBIHq.L3u@news.arco.com>
- NNTP-Posting-Host: free1-slip204.tele.queensu.ca
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.1N (Macintosh; I; 68K)
- X-URL: news:DMBIHq.L3u@news.arco.com
-
- Brian Leach <lasbfl> wrote:
- >Daniel Cotter <cotter@www.cns.uky.edu> wrote:
- >>I'm trying to write a program that will generate a set of
- >>random numbers between 3 and 18. I have several problems with
- >>this program.
- >>1. C++ always generates same number(346)
- >>2. I don't know how to give a range. I've tried 3-18, but
- >> it thinks I mean to subtract(3-18=15)
- >>3. When it does work, it's always the same number
-
- 1. Brian was right, seed the random number generator. These numbers
- are not really random, but are statistically indistinguishable from
- random numbers (ie, for most uses they are adequate as random numbers).
- The random number generator applies its algorithm to this seed to
- generate its sequence of pseudorandom numbers.
-
- 2. Typically random number generators return a real number between 0.0
- and 1.0. You want a random number between 3 and 18, a range of 15.
-
- Basically, you want to scale your random number to the same range, by
- multiplying it by 16. So now you have a real number between 0.0 and
- 16.0. Next, translate it to the same 'location' by adding 3. Now you
- have a real number between 3.0 and 19.0. Finally, take the floor of
- this number (the part before the decimal) to get a natural number
- between 3 and 18 (watch out for the 19.0 case, though, that you don't
- get 19!).
-
- The reason you want to scale by an extra number and use floor instead of
- just rounding is because with rounding, your lowest and highest values
- (3 and 18) will occur only half as likely as all the others (4, 5, ...,
- 17).
-
- Of course, this is just the logic behind it all. This normally can be
- done all in one simple, obscure line of code.
-
- --
- Wintermute <3mal5@qlink.queensu.ca> <http://qlink.queensu.ca/~3mal5/>
-
- "If I really knew how to write, I could write something that someone
- could read and it would kill them." - william s. burroughs
-
-
-